package com.edroid.droidhelper.pc.app;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.AndroidDebugBridge.IClientChangeListener;
import com.android.ddmlib.AndroidDebugBridge.IDebugBridgeChangeListener;
import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
import com.android.ddmlib.Client;
import com.android.ddmlib.IDevice;
import com.edroid.droidhelper.pc.model.AppGlobal;
import com.edroid.droidhelper.pc.model.DeviceChangeListener;
import com.edroid.droidhelper.pc.model.InstallLogManager;
import com.edroid.droidhelper.pc.model.NetwokWorker;
import com.edroid.droidhelper.pc.model.Phone;
import com.edroid.droidhelper.pc.util.FileUtils;
import com.edroid.droidhelper.pc.util.Logger;
import com.edroid.droidhelper.pc.view.LoginDialog;
import com.edroid.droidhelper.pc.view.MainFrame;
import com.edroid.droidhelper.pc.view.Toast;

public class Bootstrup extends SwingApplication implements IClientChangeListener, IDebugBridgeChangeListener,IDeviceChangeListener {
	static final Logger log = Logger.create("Bootstrup");
	
	private static Bootstrup instance;

	private Map<IDevice, Phone> connectedDevices;
	private DeviceChangeListener mDeviceChangeListener;
	private MainFrame mainFrame;
	
	
	private Bootstrup(boolean nativeLook) {
		super(nativeLook);
		instance = this;
		connectedDevices = new HashMap<IDevice, Phone>(5);
		
		initPath();
		checkLogin();
		
		NetwokWorker.post(new Runnable() {
			
			@Override
			public void run() {
				InstallLogManager.getInstance().upload();
			}
		});
	}
	
	public void cleanup() {
		stopAllDevice();
		
		AndroidDebugBridge.disconnectBridge();
		AndroidDebugBridge.terminate();
		
		NetwokWorker.shutdownAndAwaitTermination();
	}
	
	protected void close() {
		Toast.make("请稍后，正在保存数据...").show();
		
		log.i("cleaning up...");
		
		cleanup();

		log.i("cleanup done, exiting...");
		
//		InstallLogManager.getInstance().upload();
		
		super.close();
	}
	
	public void showMainWindow() {
		mainFrame = new MainFrame();
		mainFrame.setVisible(true);
		setDeviceChangeListener(mainFrame);
		
		initAdb();
	}
	
	private void initPath() {
		FileUtils.createDir(AppGlobal.PATH_APPS);
		FileUtils.createDir(AppGlobal.PATH_SCRIPTS);
		FileUtils.createDir(AppGlobal.PATH_TMP);
	}
	
	/**
	 * 检查登陆状态
	 */
	private void checkLogin() {
		LoginDialog.startLogin();
	}
	
	public void initAdb() {
		AndroidDebugBridge.init(false);
		AndroidDebugBridge.createBridge(AppGlobal.PATH_ADB, false);
//		AndroidDebugBridge.addClientChangeListener(this);
		AndroidDebugBridge.addDebugBridgeChangeListener(this);
		AndroidDebugBridge.addDeviceChangeListener(this);
		
		log.i("adb Server：" + AndroidDebugBridge.getSocketAddress());
		log.i("adb is running...");
	}
	
	public static Bootstrup getInstance() {
		return instance;
	}

	public static void main(String[] args) {
		new Bootstrup(true);
	}
	
	public void setDeviceChangeListener(DeviceChangeListener l) {
		this.mDeviceChangeListener = l;
	}
	
	private void stopAllDevice() {
		if(connectedDevices.isEmpty())
			return;
		
		for(Entry<IDevice, Phone> e : connectedDevices.entrySet()) {
			Phone phone = e.getValue();
			phone.stopInstallTask(true);
		}
	}

	@Override
	public void deviceChanged(IDevice arg0, int arg1) {
		log.i("tid=" + Thread.currentThread().getId());
		log.i("设备状态改变：" + arg0 
				+ " " + arg1 
				+ " " + arg0.getState());
		
		Phone device = connectedDevices.get(arg0);
		if(device != null) {
			device.onStateChanged(arg0, arg1);
			
			if(mDeviceChangeListener != null)
				mDeviceChangeListener.onDeviceStateChanged(device, device.isAvailable());
		}
	}

	@Override
	public void deviceConnected(IDevice arg0) {
		log.i("tid=" + Thread.currentThread().getId());
		
		log.i("设备插入：" + arg0);
		log.i("状态：" + arg0.getState().toString());
		mainFrame.setStateInfo("设备插入：" + arg0);

		Phone device = new Phone(arg0);
		connectedDevices.put(arg0, device);

		if (mDeviceChangeListener != null)
			mDeviceChangeListener.onDeviceAttached(device);
	}

	@Override
	public void deviceDisconnected(IDevice arg0) {
		log.i("tid=" + Thread.currentThread().getId());
		log.i("设备拔出：" + arg0);
		
		if(connectedDevices.containsKey(arg0)) {
			Phone device = connectedDevices.remove(arg0);
			
			device.onDisconnect();
			
			if(mDeviceChangeListener != null)
				mDeviceChangeListener.onDeviceDetached(device);
		}
	}

	@Override
	public void bridgeChanged(AndroidDebugBridge arg0) {
//		log.i("bridgeChanged:" + arg0);
	}

	@Override
	public void clientChanged(Client arg0, int arg1) {
//		log.i("clientChanged:" + arg0 + ", " + arg1);
	}
}
